/// <reference path="../../index.d.ts" />
"use strict"
let PromWxApi = require("../util/wechat").PromWxApi
module.exports = ({queryKey, dbKey} = {}) => {
	/**
	 * @type {import("egg").CbMiddle}
	 */
	let wxApi = async function (ctx, next) {

		let appInfo = {}
		if (!dbKey && !queryKey) {
			// token 
			appInfo = (await ctx.app.cache.application).find(function (o) {
				return o.id == ctx.userInfo.aid
			})
		} else {
			ctx.validate({[queryKey]: "string"}, ctx.query)
			appInfo = await ctx.service.application.getApplicationInfo({
				[dbKey]: ctx.query[queryKey]
			})
		}


		if (!appInfo) {
			ctx.throw(422, "no has app", {
				code: "invalid_param",
				errors: [{"message": "没有app", "field": "app_id", "code": "missing_app"}],
			})
			return
		}
		let {app_id, app_secret, token, encoding_aeskey, id: aid, app_type} = appInfo
		ctx.wechat = {app_id, app_secret, token, encoding_aeskey, aid, app_type}
		ctx.wechatAccount = PromWxApi.getInstance({
			token: token,
			appid: app_id,
			encodingAESKey: encoding_aeskey,
			AppSecret: app_secret
		})
		await next()
	}
	return wxApi
}